/*
 * @Descripttion: 
 * @version: 
 * @Author: TT
 * @Date: 2023-10-20 10:32:32
 * @LastEditors: TT
 * @LastEditTime: 2023-10-30 16:30:35
 */
import 'package:hzy_project_template/models/image_normal_model.dart';
import 'package:hzy_project_template/utils/image_utils.dart';
import 'package:hzy_project_template/utils/utils_index.dart';

import '../config/config_index.dart';

import '../models/user_model.dart';
import '../utils/gallery_tool.dart';

class UserC extends GetxController {
  /// 获取控制器
  static UserC get current => Get.find<UserC>();

  /// 用户模型
  UserModel? _userModel;

  /// 获取用户信息
  UserModel? get user => _userModel;

  /// 用户是否登录
  static bool get isLogin => current.user != null;

  /// 头像原图
  ImageNormalModel imageNormalModel = ImageNormalModel();

  ImageNormalModel? loaclImageModle;

  /// 退出登录
  logOut() async {
    _userModel?.status = 0;
    await configLocalUserInfo();
    await HzySpTool.saveUserInfo(
      info: _userModel?.toMap(),
      account: _userModel?.account,
    );
    imageNormalModel = ImageNormalModel();
    _userModel = null;
    update();
  }

  configLocalUserInfo() async {
    var userModel = getUserInfo();
    if (userModel != null && userModel.headImage != null) {
      loaclImageModle = ImageNormalModel(
          byte: await ImageUtils.getLocahOnlyImageBytes(
        url: userModel.headImage!,
      ));
    }
  }

  /// 更新用户信息
  updateUserInfo({
    required UserModel model,
    bool isNeedConfigHeader = false,
  }) async {
    model.status = 1;
    _userModel = model;
    dPrint(model.toMap());

    await HzySpTool.saveUserInfo(
      info: model.toMap(),
      account: model.account,
    );
    await HzySpTool.saveToken(token: model.account!);
    if (isNeedConfigHeader) {
      await configLoaclHeaderImage(model: model);
    }
    update();
  }

  configLoaclHeaderImage({
    required UserModel model,
  }) async {
    configLocalUserInfo();
    if (model.headImage != null) {
      imageNormalModel.byte = await ImageUtils.getLocahOnlyImageBytes(
        url: model.headImage!,
      );
    }
  }

  configUserImageModel({
    List? imageList,
    bool isUpdataLocal = false,
  }) async {
    showNormalLoadMsg(msg: '更新中...');
    for (var element in imageList ?? []) {
      imageNormalModel = element is ImageNormalModel
          ? element
          : await GalleryTool.configImageModelWithBytesCompress(
              type: 0,
              data: element,
            );
    }
    _userModel?.headImage = await ImageUtils.saveOnlyWithbytes(
      bytes: imageNormalModel.byte!,
      type: "headerImage",
    );

    updateUserInfo(model: _userModel!);
  }
}
